package com.jcj.jcjregistry.cluster;

import lombok.extern.slf4j.Slf4j;

import java.util.List;

@Slf4j
public class Election {
    public void electLeader(List<Server> servers) {
        List<Server> masters = servers.stream().filter(Server::isStatus)
                .filter(Server::isLeader).toList();
        if (masters.size() == 0) {
            log.info(" 主不存在，开始选举 : " + servers);
            elect(servers);
        } else if (masters.size() == 1) {
            log.info(" 不需要选举 : " + masters.get(0));
        } else {
            log.info(" 超过1个主，开始选举 : " + servers);
            elect(servers);
        }
    }

    private void elect(List<Server> servers) {
        Server candidate = null;
        for (Server server : servers) {
            server.setLeader(false);
            if (server.isStatus()) {
                if (candidate == null) {
                    candidate = server;
                } else {
                    if (candidate.hashCode() > server.hashCode()) {
                        candidate = server;
                    }
                }
            }
        }
        if (candidate != null) {
            candidate.setLeader(true);
            log.info("选举成功，" + candidate);
        } else {
            log.error("选举失败，" + servers);
        }
    }
}
